<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Product extends Backend_Controller {

	const __IMG_REGEXP__ = '/<img.*?\"([^\"]*(jpg|bmp|jpeg|gif|png)).*?>/i';

	/**
	 * 构造函数
	 */
	public function __construct() {
		parent::__construct();
		// 加载product模型
		$this->load->model('backend/Product_model', 'Product');
		$this->load->model('backend/Album_model', 'Album');
		// 加载验证类
		$this->load->library('form_validation');
	}

	/**
	 * 显示后台个人中心下的查看产品
	 */
	public function index() {
		$this->isValidRequest();
		$result = $this->Product->getProductAll($this->page, $this->input->post());
		$this->load->model('backend/Category_model', 'Category');
		$result['categoryList'] = $this->Category->categoryList();
		$this->load->view('backend/product/index', $result);
	}

	public function multiAdd() {
		$this->isValidRequest();

		if ($this->isPost()) {
			$products = $this->input->post('products');
			$time = time();
			$data = array();
			foreach ($products as $k => $v) {
				$data[$k]['name'] = $v['name'];
				$data[$k]['price'] = $v['price'] * 100;
				$data[$k]['market_price'] = $v['price'] * 100;
				$data[$k]['status'] = $v['status'];
				$data[$k]['category_id'] = $v['category_id'];
				$data[$k]['stock'] = $v['stock'];
				$data[$k]['isHot'] = $v['isHot'];
				$data[$k]['isLimit'] = $v['isLimit'];
				$data[$k]['limit_num'] = $v['limit_num'];
				$data[$k]['specs'] = $v['specs'];
				$data[$k]['thumbnail_id'] = $v['attachment_id'];
				$data[$k]['serial'] = empty($v['serial']) ? date('ymd') . str_pad($k, 3, '0', STR_PAD_LEFT) . rand(1000, 9999):$v['serial'];
				$data[$k]['created_at'] = $time;
				$data[$k]['updated_at'] = $time;
			}
			$result = $this->Product->addMulti($data);
			if ($result) {
				$this->renderJson(200, '', array(
					'navTabId' => 'backendproductindex',
					'callbackType' => 'closeCurrent'
				));
			}
			$this->renderJson(300);
		}
		$this->load->model('backend/Category_model', 'Category');
		$data['categoryList'] = $this->Category->categoryList();
		$this->load->view('backend/product/multiAdd', $data);
	}
	
	/**
	 * 批量修改价格
	 */
	public function batch()
	{
		
		if ($this->isPost()) {
			
			if($this->input->post('type') == 'price'){
				$ids = $this->input->post('ids');
				$status=$this->input->post('status');
				if($status =='10'){
					
				}else if($status == '0'){
					
				}
				
			}
		}
		$this->load->view('backend/product/batch');
	}
	
	
	

	/**
	 * 添加产品
	 */
	public function add() {
		$this->isValidRequest();

		if ($this->isPost()) {
			$this->form_validation->validateData(array(
				'name',
				'specs',
				'price',
				'stock',
				'attachment_id',
				'attachment_filename',
				'status',
				'content',
				'category_id',
				'isHot',
				'hot_id',
				'hot_filename',
				'isLimit',
				'limit_num'
					), array(
				array(
					'name',
					'required'
				),
				array(
					'specs',
					'required'
				),
				array(
					'price',
					'required|numeric'
				),
				array(
					'stock',
					'required|integer'
				),
				array(
					'attachment_id',
					'required|integer'
				),
				array(
					'status',
					'required|integer'
				),
				array(
					'category_id',
					'required|integer'
				),
				array(
					'isHot',
					'required|in_list[0,10]'
				),
				array(
					'isLimit',
					'required|in_list[0,10]'
				),
				array(
					'limit_num',
					'required|in_list[0,10]'
				),
			));

			if ($this->form_validation->hasErrors()) {
				$this->renderJson(300, $this->form_validation->error);
			}

			$spec = $this->post('multiSpec');
			$specs = array();
			if (!empty($spec)) {
				foreach ($spec as $val) {
					if (!empty($val ['spec']) && !empty($val['price'])) {
						$specs [] = array('spec' => $val ['spec'], 'price' => $val['price'] * 100, 'stock' => $val['stock']);
					}
				}
			}

			$res = $this->checkText($this->form_validation->content);

			$data = array(
				'name' => $this->form_validation->name,
				'specs' => $this->form_validation->specs,
				'price' => $this->form_validation->price * 100,
				'market_price' => $this->form_validation->price * 100,
				'stock' => $this->form_validation->stock,
				'thumbnail_id' => $this->form_validation->attachment_id,
				'thumbnail' => $this->form_validation->attachment_filename,
				'status' => $this->form_validation->status,
				'content' => $res ['content'],
				'isLimit' => $this->form_validation->isLimit,
				'isHot' => $this->form_validation->isHot,
				'hot_img_id' => $this->form_validation->hot_id,
				'hot_img' => $this->form_validation->hot_filename,
				'limit_num' => $this->form_validation->limit_num,
				'category_id' => $this->form_validation->category_id,
				'serial' => date('ymd') . time() . rand(1000, 9999),
				'created_at' => time()
			);
			$insertId = $this->Product->addProduct($data, $specs, $res ['images']);
			if ($insertId) {
				$this->renderJson(200, '', array(
					'navTabId' => 'backendproductindex',
					'callbackType' => 'openTab',
					'tabid' => 'backendproductimages',
					'url' => site_url("backend/product/images?id={$insertId}"),
					'title' => '图片处理',
					'fresh' => TRUE
				));
			}

			if (!empty($res ['remote'])) {
				foreach ($res ['remote'] as $v) {
					$path = realpath($v);
					if (file_exists($path)) {
						unlink($path);
					}
				}
				$this->Album->delete(array(
					'img' => $res ['remote']
				));
			}

			$this->renderJson(300);
		}
		$this->load->model('backend/Category_model', 'Category');
		$data['categoryList'] = $this->Category->categoryList();
		$this->load->view('backend/product/add', $data);
	}

	/**
	 * 添加商品图片
	 */
	public function images() {
		if ($this->isPost()) {
			$this->form_validation->validateData(array(
				'id',
				'width',
				'height'
					), array(
				array(
					'id',
					'required|integer|greater_than[0]'
				),
				array(
					'width',
					'required|integer'
				),
				array(
					'height',
					'required|integer'
				)
			));

			if ($this->form_validation->hasErrors()) {
				$this->renderJson(10005, $this->form_validation->error);
			}

			$ratio = $this->post('ratio', 'on') == 'on' ? true : false;
			$images = $this->post('images');
			$upload_path = config_item('upload_path') . '/product/' . date('Ymd');
			if (!is_dir($upload_path)) {
				mkdir($upload_path, 0755, true);
			}
			if (!empty($images) && is_array($images)) {
				$rows = $this->Album->getAll($images, 'img');
				$dataInsert = array();
				$tpl = array(
					'source_id' => $this->form_validation->id,
					'type' => '1',
					'created_at' => time(),
					'from' => '1'
				);
				foreach ($rows as $v) {
					if (file_exists($v ['img'])) {
						$ext = pathinfo($v ['img'], PATHINFO_EXTENSION);
						$filename = $upload_path . '/' . time() . rand(1000, 9999) . '.' . $ext;
						$result = copy($v ['img'], $filename);
						if ($result) {
							$tpl ['img'] = $filename;
							$dataInsert [] = $tpl;
						}
					}
				}

				if (!empty($dataInsert) && !$this->Album->add($dataInsert)) {
					foreach ($dataInsert as $tpl) {
						if (file_exists($tpl ['img'])) {
							unlink($tpl ['img']);
						}
					}
				}
			}

			$result = $this->Album->get_result(array(
				'source_id' => $this->form_validation->id,
				'type' => '1',
				'from' => '1'
					), array(
				'field' => 'img'
			));
			$string = '';
			if ($this->form_validation->width || $this->form_validation->height) {
				$string = $this->imagesResize($result, $this->form_validation->width, $this->form_validation->height, $ratio);
			}
			$this->renderJson(200, $string, array(
				'navTabId' => 'backendproductindex',
				'callbackType' => 'closeCurrent'
			));
		}

		$product_id = intval($this->get('id'));
		if ($product_id < 1) {
			$this->renderJson(10005);
		}
		$data ['data'] = $this->Album->get_result(array(
			'source_id' => $product_id,
			'type' => '2',
			'from' => '1'
		));
		$this->load->view('backend/product/images', $data);
	}

	/**
	 * 产品规格
	 */
	public function speces() {
		$this->isValidRequest();
		$id = $this->input->get('id');
		$data = $this->Product->getSpeces();

		$this->load->view(200, $data);
	}

	/**
	 * 删除产品
	 */
	public function delete() {
		$this->isValidRequest();
		$ids = $this->input->post_get('ids');
		if ($this->Product->deleteProduct($ids)) {
			$this->renderJson(200, '', array(
				'navTabId' => 'backendproductindex'
			));
		}

		$this->renderJson(300);
	}

	/**
	 * 修改产品信息
	 */
	public function edit() {
		$this->isValidRequest();

		if ($this->isPost()) {
			$this->form_validation->validateData(array(
				'id',
				'name',
				'specs',
				'price',
				'stock',
				'attachment_id',
				'status',
				'content',
				'category_id',
				'isHot',
				'hot_id',
				'isLimit',
				'limit_num',
					), array(
				array(
					'id',
					'required|integer|greater_than[0]'
				),
				array(
					'name',
					'required'
				),
				array(
					'specs',
					'required'
				),
				array(
					'price',
					'required|numeric'
				),
				array(
					'stock',
					'required|integer'
				),
				array(
					'attachment_id',
					'required|integer'
				),
				array(
					'status',
					'required|integer'
				),
				array(
					'category_id',
					'required|integer'
				),
				array(
					'isHot',
					'required|in_list[0,10]'
				),
				array(
					'isLimit',
					'required|in_list[0,10]'
				)
			));

			if ($this->form_validation->hasErrors()) {
				$this->renderJson(300, $this->form_validation->error);
			}

			$res = $this->checkText($this->form_validation->content, $this->form_validation->id);

			$data = array(
				'name' => $this->form_validation->name,
				'price' => $this->form_validation->price * 100,
				'stock' => $this->form_validation->stock,
				'thumbnail_id' => $this->form_validation->attachment_id,
				'status' => $this->form_validation->status,
				'content' => $res ['content'],
				'isLimit' => $this->form_validation->isLimit,
				'isHot' => $this->form_validation->isHot,
				'hot_img_id' => $this->form_validation->hot_id,
				'limit_num' => $this->form_validation->limit_num,
				'category_id' => $this->form_validation->category_id,
				'updated_at' => time(),
			);
			$update = $this->Product->updateProduct($data, $this->form_validation->id);
			if ($update) {
				$this->renderJson(200, '', array(
					'navTabId' => 'backendproductindex',
					'callbackType' => 'closeCurrent'
				));
			}

			if (!empty($res ['remote'])) {
				foreach ($res ['remote'] as $v) {
					$path = realpath($v);
					if (file_exists($path)) {
						unlink($path);
					}
				}
				$this->Album->delete(array(
					'img' => $res ['remote']
				));
			}

			$this->renderJson(300);
		}
		$id = intval($this->get('id'));
		$data = $this->Product->findProduct($id);
		$this->load->model('backend/Category_model', 'Category');
		$data['categoryList'] = $this->Category->categoryList();
		$this->load->view('backend/product/edit', $data);
	}

	private function upload($source_id = 0, $type = '2') {
		$config ['upload_path'] = config_item('upload_path') . '/product/' . date('Ymd');
		if (!is_dir($config ['upload_path'])) {
			mkdir($config ['upload_path'], 0755, true);
		}
		$config ['file_name'] = time() . rand(1000, 9999);
		$config ['allowed_types'] = 'jpg|bmp|jpeg|gif|png';

		$data = array(
			'status' => 300,
			'msg' => ''
		);

		$this->load->library('upload', $config);
		if (!$this->upload->do_upload('filedata')) {
			$data ['msg'] = $this->upload->display_errors();
		} else {
			$dataInsert = array(
				'source_id' => $source_id,
				'img' => $config ['upload_path'] . '/' . $this->upload->data('file_name'),
				'type' => $type . '', // 类型默认链接
				'from' => '1', // 来源商品
				'created_at' => time()
			);
			$data ['id'] = $this->Album->addOne($dataInsert);
			$data ['filename'] = $dataInsert['img'];
			$data ['status'] = 200;
			$data ['msg'] = base_url($dataInsert ['img']);
		}
		return $data;
	}

	/**
	 * xhEditor 上传
	 */
	public function xhUpload() {
		if (!empty($_FILES)) {
			$data = array(
				'err' => '',
				'msg' => ''
			);
			$id = intval($this->get('id'));
			$res = $this->upload($id);
			if ($res ['status'] == 200) {
				$data ['msg'] = $res ['msg'];
			} else {
				$data ['err'] = $res ['msg'];
			}
			echo json_encode($data);
			die();
		}
	}

	public function multiUpload() {
		if (!empty($_FILES)) {
			$source_id = intval($this->post('source_id', 0));
			$type = intval($this->post('type', 2));
			$res = $this->upload($source_id, $type);
			if ($res ['status'] == 200) {
				$this->renderJson(200, $res ['msg'], array(
					'id' => $res ['id'],
					'filename' => $res['filename'],
					'id]' => $res ['id'],
					'filename]' => $res['filename']
				));
			} else {
				show_error($res ['msg']);
			}
		}
		$this->load->view('backend/product/upload');
	}

	/**
	 * 检测产品内容
	 *
	 * @param string $content        	
	 * @param string $token        	
	 * @return array array('content','remote','images')
	 */
	private function checkText($content, $source_id = 0) {
		$res = array(
			'content' => '',
			'remote' => array(),
			'images' => array()
		);
		if (empty($content)) {
			return $res;
		}

		$host = trim(base_url(), '/');
		$remote = $this->post('remote');
		$dellink = $this->post('dellink');
		// $content = html_entity_decode($content);

		$matchs = array();

		// 删除非站内链接
		if ($dellink === 'on') {
			preg_match_all("#<a([^>]*)>(.*)<\/a>#iU", $content, $matchs);
			if ($matchs [0]) {
				foreach ($matchs [0] as $k => $val) {
					$a_text = $matchs [1] [$k];
					if ((strpos($a_text, 'http://') !== false || strpos($a_text, 'https://') !== false) && strpos($a_text, $host) === false) {
						$search_arr [] = $val;
						$replace_arr [] = $matchs [2] [$k];
					}
				}
				$content = str_replace($search_arr, $replace_arr, $content);
			}
		}

		$upload_path = config_item('upload_path') . '/product/' . date('Ymd');
		if (!is_dir($upload_path)) {
			mkdir($upload_path, 0755, TRUE);
		}
		$regexp = self::__IMG_REGEXP__;
		// $regexp = '/href="(.*?)"/i';
		// 远程图片本地化

		preg_match_all($regexp, $content, $matchs);
		$img_arr = $matchs [1];

		if (count($img_arr) > 0) {
			foreach ($img_arr as $k => $img) {
				if (strpos($img, $host) !== false) {
					$res ['images'] [] = trim(str_replace(base_url(), '', $img), '/');
					continue;
				}
				if ($remote === 'on') {
					$path_info_arr = parse_url($img);
					$path_arr = pathinfo($path_info_arr ['path']);
					$file_name = time() . rand(1000, 9999) . '.' . $path_arr ['extension'];
					$upload_file = $upload_path . '/' . $file_name;

					if (file_put_contents($upload_file, $this->getRemote($img))) {
						$res ['remote'] [] = $upload_file;
						$res ['images'] [] = $upload_file;
						$dataInsert = array(
							'source_id' => $source_id,
							'img' => $upload_file,
							'type' => '2', // 类型链接
							'from' => '1', // 来源商品
							'created_at' => time()
						);
						$this->Album->addOne($dataInsert);
						$content = str_replace($img, base_url($upload_file), $content);
					}
				}
			}
		}
		$res ['content'] = $content;
		return $res;
	}

	private function getRemote($url) {
		$ch = curl_init();
		$timeout = 5;
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		$img = curl_exec($ch);
		curl_close($ch);
		return $img;
	}

	private function imagesResize($images, $width, $height, $ratio) {
		$num = 0;
		$config ['image_library'] = 'gd2';
		$config ['maintain_ratio'] = $ratio;
		if($width) {
			$config ['width'] = $width;
		}
		if($height) {
			$config ['height'] = $height;
		}
		
		if (is_array($images)) {
			$this->load->library('image_lib');
			foreach ($images as $v) {
				$config ['source_image'] = $v ['img'];
				$this->image_lib->initialize($config);
				if ($this->image_lib->resize()) {
					$num ++;
				}
			}
		} elseif (is_string($images)) {
			$config ['source_image'] = realpath($images);
			$this->image_lib->initialize($config);
			if ($this->image_lib->resize()) {
				$num ++;
			}
		}
		$this->lang->load('label');
		return sprintf($this->lang->line('effectRows'), $num);
	}

	
	/**
	 * 上架和下架
	 */
	public function UpAndDown()
	{
		$this->load->library('form_validation');
		$this->form_validation->validateData(array(
			'db', 'value', 'primary', 'id'
		), array(
			array('db','required'),
			array('value', 'required'),
			array('primary', 'required'),
			array('id', 'integer|greater_than[0]')
		));
		if($this->form_validation->hasErrors()) {
			$this->renderJson(300, $this->form_validation->error);
		}
		$table = $field = '';
		sscanf($this->form_validation->db, '%[^.].%[^.]', $table, $field);
		if(!$table || !$field || !$this->db->table_exists($this->db->dbprefix($table)) || !$this->db->field_exists($field, $this->db->dbprefix($table))) {
			$this->renderJson(300, 'table:'.$table . ' field:'.$field. ' table_exists:' . $this->db->table_exists($this->db->dbprefix($table)));
		}
		$this->db->update($table, array($field=>  $this->form_validation->value), array($this->form_validation->primary =>  $this->form_validation->id));
		if($this->db->affected_rows() > 0) {
			//$this->renderJson(200);
			
			//开始记录
			
			
		}
		$this->renderJson(300);
	}
	

}
